﻿
let publicUrl = 'https://geo.datav.aliyun.com/areas_v3/bound/';

async function initChart(chartId) {
    let chart = echarts.init(document.getElementById(chartId));
    let alladcode = await getGeoJson('all.json');
    let hebeiGeoJson = await getGeoJson('130000_full.json');
    initEcharts(hebeiGeoJson, '河北省', chart, alladcode);
}
// province city country
var level = 'province';

function initEcharts(geoJson, name, chart, alladcode) {
    echarts.registerMap(name, geoJson);

    let option = {
        title: {
            text: name,
            left: 'center'
        },
        series: [{
            type: 'map',
            map: name,
            itemStyle: {
                areaColor: '#1890ff',
            }
        }],
    };
    chart.setOption(option);
    chart.off("click");
    chart.on('click', params => {

        let clickRegionCode = alladcode.filter(areaJson => areaJson.name === params.name)[0].adcode;

        if (level === 'province') {
            getGeoJson(clickRegionCode + '_full.json')
                .then(regionGeoJson => {
                    initEcharts(regionGeoJson, params.name, chart, alladcode);
                    level = 'city';
                })
                .catch(err => {
                    getGeoJson('130000_full.json').then(
                        hebeiGeoJson => {
                            initEcharts(hebeiGeoJson, '河北省', chart, alladcode);
                            level = 'province';
                        }

                    );
                });
        } else if (level === 'city' || level === 'country') {
            getGeoJson(clickRegionCode + '.json')
                .then(regionGeoJson => {
                    initEcharts(regionGeoJson, params.name, chart, alladcode);
                    if (level === 'country') {
                        getGeoJson('130000_full.json').then(
                            hebeiGeoJson => {
                                initEcharts(hebeiGeoJson, '河北省', chart, alladcode);
                                level = 'province';
                            }
                        );
                    }
                    if (level === 'city') {
                        level = 'country';
                    }
                    
                })
                .catch(err => {
                    getGeoJson('130000_full.json').then(
                        hebeiGeoJson => {
                            initEcharts(hebeiGeoJson, '河北省', chart, alladcode);
                            level = 'province';
                        }

                    );
                });
        }



    });
}

async function getGeoJson(jsonName) {
    return await $.get(publicUrl + jsonName);
}